package com.swm.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.swm.mapper.StockMapper;
import com.swm.pojo.Stock;
import org.apache.ibatis.session.SqlSession;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 师文明
 * @data 2024/12/23 下午3:11
 **/
public class getStockDayData3 {

    public static double sum;
    public static double sum3;
    public static double sum5;
    public static double sum10;
    public static int num0;
    public static int numu;
    public static int numd;
    public static int numu3;
    public static int numd3;
    public static int numu5;
    public static int numd5;
    public static int numu10;
    public static int numd10;
    static SqlSession sqlSession = SqlSessionUtil.openSession();
    static StockMapper mapper = sqlSession.getMapper(StockMapper.class);

    public static List<Stock> getStcokList() {
        List<Stock> stocks = mapper.selectAllStock();
        JSONObject jsonObject = new JSONObject();

        for (Stock stock : stocks) {
            String code = stock.getCode();
            int type = stock.getType();
            jsonObject.put(code, type);

        }
        return stocks;
    }

    public static void main(String[] args) throws Exception {

        ExecutorService executorService = Executors.newFixedThreadPool(50);
        //获取所有股票列表
        List<Stock> stcokList = getStcokList();
        for (Stock stock : stcokList) {
            executorService.execute(() -> {
                try {
                    getData(stock.getCode(), stock.getType());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

        //executorService.shutdown();
        Thread.sleep(40000);
        double v = 0;
        double v3 = 0;
        double v5 = 0;
        double v10 = 0;
        if (num0 != 0 && sum != 0) {
            v = sum / num0;
        }
        if (num0 != 0 && sum3 != 0) {
            v3 = sum3 / num0;
        }
        if (num0 != 0 && sum5 != 0) {
            v5 = sum5 / num0;
        }
        if (num0 != 0 && sum10 != 0) {
            v10 = sum10 / num0;
        }

        System.out.println(("一天后平均涨幅：" + v));//+"\r\n"));
        System.out.println(("3天后平均涨幅：" + v3));//+"\r\n"));
        System.out.println(("5天后平均涨幅：" + v5));//+"\r\n"));
        System.out.println(("10天后平均涨幅：" + v10));//+"\r\n"));

        DecimalFormat df = new DecimalFormat("#0.00");

        System.out.println(("一天后涨的次数：" + numu + "  跌的次数：" + numd + "  上涨概率： " + df.format((double) numu / num0)));//+"\r\n"));
        System.out.println(("3天后涨的次数：" + numu3 + "  跌的次数：" + numd3 + "  上涨概率： " + df.format((double) numu3 / num0)));//+"\r\n"));
        System.out.println(("5天后涨的次数：" + numu5 + "  跌的次数：" + numd5 + "  上涨概率： " + df.format((double) numu5 / num0)));//+"\r\n"));
        System.out.println(("10天后涨的次数：" + numu10 + "  跌的次数：" + numd10 + "  上涨概率： " + df.format((double) numu10 / num0)));//+"\r\n"));

        // 关闭线程池，以优雅的方式
        // 关闭线程池，以优雅的方式
    }

    public static void getData(String code, int type) throws Exception {

        String data = getWebData(code, type);
        if (data == null) {
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get("data") != null) {
            JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            String name = jsonObject1.get("name").toString();
            JSONArray klines = JSONArray.parse(jsonObject1.get("klines").toString());
            double price0 = Double.parseDouble(klines.get(klines.size() - 1).toString().split(",")[2]);
            if (klines.size() > 130) {
                int size = klines.size();
                if (klines.size() > 220) {
                    size = 220;
                }
                //最近80天内放量
                for (int i = 11; i < size - 120; i++) {
                    //最近120天内成交量集合
                    List<Double> numbers = new ArrayList<>();
                    //最近120天内收盘价集合
                    List<Double> prices = new ArrayList<>();


                    for (int j = 0; j < 120; j++) {
                        //成交量
                        double v2 = Double.parseDouble(klines.get(klines.size() - (i + j)).toString().split(",")[5]);
                        numbers.add(v2);
                        //收盘价
                        double p2 = Double.parseDouble(klines.get(klines.size() - (i + j)).toString().split(",")[2]);
                        prices.add(p2);
                    }
                    // 使用List的sort()方法和Lambda表达式进行排序
                    numbers.sort(Double::compare);
                    // 使用List的sort()方法和Lambda表达式进行排序
                    prices.sort(Double::compare);

                    //今日收盘价
                    double p0 = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[2]);

                    //今日成交额
                    double v0 = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[5]);
                    //1天前成交额
                    double v1 = Double.parseDouble(klines.get(klines.size() - (i + 1)).toString().split(",")[5]);
                    //2天前成交额
                    double v2 = Double.parseDouble(klines.get(klines.size() - (i + 2)).toString().split(",")[5]);
                    //3天前成交额
                    double v33 = Double.parseDouble(klines.get(klines.size() - (i + 3)).toString().split(",")[5]);
                    //3天前成交额
                    double v4 = Double.parseDouble(klines.get(klines.size() - (i + 4)).toString().split(",")[5]);
                    //5天前成交额
                    double v55 = Double.parseDouble(klines.get(klines.size() - (i + 5)).toString().split(",")[5]);

                    double multiple = 2;

                    //昨日成交比五天前成交量倍数大于2
                    boolean b = v0 / v1 > multiple || v0 / v2 > multiple || v0 / v33 > multiple || v0 / v4 > multiple || v0 / v55 > multiple;
                    //当天涨幅
                    double vd = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[8]);

                    if (vd < 0 && p0 < prices.get(9) && v0 > numbers.get(109)) {
                        //第二天涨幅
                        double v = Double.parseDouble(klines.get(klines.size() - i + 1).toString().split(",")[8]);
                        /*if(v>9.7||v<-9.7){
                            System.out.println(name+" : "+klines.get(klines.size() - i).toString().split(",")[0]+"，当日涨幅： "+vd+"  次日涨幅："+v);
                        }*/

                        System.out.println(name + " : " + klines.get(klines.size() - i).toString().split(",")[0] + "，次日涨幅" + v);
                        //当天收盘
                        double vs0 = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[2]);
                        //第3天收盘价
                        double vs03 = Double.parseDouble(klines.get(klines.size() - i + 3).toString().split(",")[2]);
                        double v3 = (vs03 - vs0) / vs0;

                        //第5天收盘价
                        double vs05 = Double.parseDouble(klines.get(klines.size() - i + 5).toString().split(",")[2]);
                        double v5 = (vs05 - vs0) / vs0;

                        //第10天收盘价
                        double vs010 = Double.parseDouble(klines.get(klines.size() - i + 10).toString().split(",")[2]);
                        double v10 = (vs010 - vs0) / vs0;
                        /*double v3 = Double.parseDouble(klines.get(klines.size() - i + 3).toString().split(",")[8]);
                        double v5 = Double.parseDouble(klines.get(klines.size() - i + 5).toString().split(",")[8]);
                        double v10 = Double.parseDouble(klines.get(klines.size() - i + 10).toString().split(",")[8]);*/
                        sum += v;
                        sum3 += v3;
                        sum5 += v5;
                        sum10 += v10;

                        num0++;
                        if (v > 0) {
                            numu++;
                        } else {
                            numd++;
                        }

                        if (vs03 > vs0) {
                            numu3++;
                        } else {
                            numd3++;
                        }

                        if (vs05 > vs0) {
                            numu5++;
                        } else {
                            numd5++;
                        }

                        if (vs010 > vs0) {
                            numu10++;
                        } else {
                            numd10++;
                        }

                    }
                }
                
              /*  //3天前成交额
                double v1 = Double.parseDouble(klines.get(klines.size() - (num+3)).toString().split(",")[5]);
                //5天前成交额
                double v2 = Double.parseDouble(klines.get(klines.size() - (num+5)).toString().split(",")[5]);

                //昨日成交比五天前成交量倍数大于2
                boolean b5 = v / v1 > 2 || v/v2>2;

                //放量2倍以上 涨幅大于0小于4  一个月内振幅小于10
                if(b0&&b1*//*&&b2*//*&&b5){
                    String url1="https://51.push2.eastmoney.com/api/qt/stock/sse?fields=f31,f50,f71,f116,f117,f168&secid="+type+"."+code;

                    JSONObject webData = getWebData(url1);
                    //市值
                    Double v5 = Double.parseDouble(webData.get("f117").toString()) / 100000000;
                    //量比
                    Double v6 = Double.parseDouble(webData.get("f50").toString())/100;
                    //换手率
                    Double v7 = Double.parseDouble(webData.get("f168").toString())/100;

                    Double v9 = Double.parseDouble(webData.get("f71").toString())/100;
                    //当前价格
                    double v10 = Double.parseDouble(klines.get(klines.size() - num).toString().split(",")[2]);
                    //市值大于50亿 小于200亿   量比大于1  换手率大于5小于10  收盘高于平均价
                    if(!name.startsWith("ST")&&!name.startsWith("*ST") &&!name.startsWith("退市")  &&v5>30&&v5<200   &&v6>1  &&v7>5&&v7<10  &&v9<v10 ) {
                        System.out.println(name+ "  ："*//*+v4*//*);
                    }
                }*/
            }
        }
    }


    public static String getWebData(String code, int type) {
        String data = null;
        try {
            // 连接到新浪财经接口
            String url = "https://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f116,f117&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&beg=0&end=20500101&rtntype=6&secid=" + type + "." + code + "&klt=101&fqt=1";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Cookie", "qgqp_b_id=488de58836c5f30c189b9ad4c700b9f5; st_si=04137509447995; websitepoptg_api_time=1734056942833; st_asi=delete; HAList=ty-1-603999-%u8BFB%u8005%u4F20%u5A92%2Cty-0-002888-%u60E0%u5A01%u79D1%u6280%2Cty-0-002269-%u7F8E%u90A6%u670D%u9970%2Cty-0-000813-%u5FB7%u5C55%u5065%u5EB7%2Cty-0-002045-%u56FD%u5149%u7535%u5668%2Cty-0-300059-%u4E1C%u65B9%u8D22%u5BCC%2Cty-1-688605-N%u5148%u950B%2Cty-1-000001-%u4E0A%u8BC1%u6307%u6570; st_pvi=62081555482493; st_sp=2024-12-11%2010%3A26%3A42; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=60; st_psi=20241213164756225-113200301201-5528754653");
            // 设置连接超时时间为 10 秒
            con.setConnectTimeout(10000);
            // 设置读取超时时间为 10 秒
            con.setReadTimeout(10000);
            // 从数据源获取实时股票数据
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            con.disconnect();
            data = response.toString();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            //e.printStackTrace();
        }

        return data;
    }


}

